//==============================================================================
#include "ClientReceiver.h"

//==============================================================================
ClientReceiver::ClientReceiver(GameClient* client)
{
	setClient(client);
	setIsReceiving(true);
}
//------------------------------------------------------------------------------
ClientReceiver::~ClientReceiver(void)
{
}
//------------------------------------------------------------------------------
void ClientReceiver::setClient(GameClient* client)
{
	this->client = client;
}
//------------------------------------------------------------------------------
GameClient* ClientReceiver::getClient()
{
	return this->client;
}
//------------------------------------------------------------------------------
void ClientReceiver::setIsReceiving(bool flag)
{
	this->_isReceiving = flag;
}
//------------------------------------------------------------------------------
bool ClientReceiver::isReceiving()
{
	return this->_isReceiving;
}
//------------------------------------------------------------------------------
DWORD ClientReceiver::run(void)
{
	return startReceivingUpdates();
}
//------------------------------------------------------------------------------
int ClientReceiver::startReceivingUpdates(void)
{
	ByteBuffer recvbuf;
	try
	{
		while(isReceiving())
		{
		
			getClient()->getSocket()->doReceiveComplete(&recvbuf);
			Message* message = new Message();
			message->unmarshal(&recvbuf);
			getClient()->getInputQueueLock()->adquire();
			getClient()->getInputQueue()->push(message);
			getClient()->getInputQueueLock()->release();
		}
	}
	catch (NetworkException &ne)
	{
		int errorCode = WSAGetLastError();
		cout << "recv failed with error: " << errorCode << endl;
		getClient()->setIsConnectionError(true);
	}
	return 0;
}
//------------------------------------------------------------------------------
void ClientReceiver::stopReceivingUpdates(void)
{
	setIsReceiving(false);
}